package com.chunuo.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chunuo.eduservice.entity.EduSubject;
import com.chunuo.eduservice.entity.excel.SubjectData;
import com.chunuo.eduservice.entity.vo.SubjectVo;
import com.chunuo.eduservice.listener.ExcelDataListener;
import com.chunuo.eduservice.mapper.EduSubjectMapper;
import com.chunuo.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-04
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {

        try {
            //文件输入流
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new ExcelDataListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SubjectVo> findTreeSubject() {
        List<EduSubject> list = this.list(null);
        List<SubjectVo> collect = list.stream().filter(item -> {
            if (item.getParentId().equalsIgnoreCase("0")) {
                return true;
            }
            return false;
        }).map(item -> {
            SubjectVo vo = new SubjectVo();
            BeanUtils.copyProperties(item, vo);
            vo.setChildren(findChildren(vo.getId()));
            return vo;
        }).sorted((item1,item2)->{
            return item1.getSort() - item2.getSort();
        }).collect(Collectors.toList());

        return collect;
    }

    private List<EduSubject> findChildren(String id) {
        List<EduSubject> children = this.list(new QueryWrapper<EduSubject>().eq("parent_id", id)).stream().sorted((item1, item2) -> {
            return item1.getSort() - item2.getSort();
        }).collect(Collectors.toList());
        return children;
    }
}
